#!/usr/bin/env lua

--FFTempl
--by Frantisek Fuka
--See http://fftempl.googlecode.com

--This is FFTempl loader which must never fail
_G.FFTEMPL = {debug = {log={}}}

function FFTEMPL.log(str)
	table.insert(FFTEMPL.debug.log, tostring(str))
end

FFTEMPL.error_HTML = function (str)
	local debugtext = table.concat(FFTEMPL.debug.log,"<p>\n")
	if debugtext == "" then
		 debugtext="No debug text! <i>(You can log debug messages yourself by calling FFTEMPL.log() function)</i>"
	end
	return('<html><body><h1>FFTempl Error!</h1><pre>' .. str .. '</pre>If you think this is an error in FFTEMPL itself (as opposed to error in your FFTEMPL plugin), please check <a href=http://fftempl.googlecode.com>fftempl.googlecode.com</a>.<p><h3>FFTEMPL DEBUG OUTPUT FOLLOWS:</h3><p>'..debugtext..'</body></html>')
end

FFTEMPL.err_fun = function(errstat)
	local tback = debug.traceback(errstat)
	local start,msg,rest = tback:match("^(%S- )([^\n]*)(.+)$")
	if rest == rest then
		tback = "<b>"..tostring(start) .. "<font color=red>"..tostring(msg).."</font></b>"..tostring(rest)
	end
	return tback
end

print("Content-type: text/html; charset=UTF-8\n\n")
local status,result = xpcall(function() return dofile 'fftempl_core.lua' end, FFTEMPL.err_fun)
if not status then
	print(FFTEMPL.error_HTML(result))
else
	if args.debug=='messages' then print(table.concat(FFTEMPL.debug.log,"<p>\n")) end --if the URL contains parameter "debug=messages"
	print(result)
end
